<?php
//
//	file: includes/acp/acp_advlog_manage.php
//	begin: 30/04/2007
//	$Author: christopher $
//	$Revision: 14 $
//	$Date: 2007-10-08 14:55:03 +0000 (Mon, 08 Oct 2007) $
//	license: http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
//
//	description: View and delete logs

if ( !defined('IN_PHPBB') )
{
	die('Hack attempt');
}

// ok, we will need forums as well auths
if ( !is_object($forums) )
{
	include_once($config->url('includes/class_forums'));
	$forums = new forums();
	$forums->read();
}
$caches = array();
if ( !$user->cache[POST_FORUM_URL] )
{
	$caches[] = POST_FORUM_URL;
}
if ( !$user->cache[POST_FORUM_URL . 'jbox'] )
{
	$caches[] = POST_FORUM_URL . 'jbox';
}
if ( !empty($caches) )
{
	$user->get_cache(array(POST_FORUM_URL, POST_FORUM_URL . 'jbox'));
}

$cp_title = 'Logs_title';
$cp_title_explain = 'Logs_explain';

$available_sort = array(
	'actdays'	=> 'Sort_Actiontime',
	'moderator'	=> 'Sort_Username',
	'type'		=> 'Sort_Log_Type',
	'forum'		=> 'Sort_Forum',
);
$sort_fields = array(
	'actdays'	=> 'l.log_time',
	'moderator'	=> 'max_username',
	'type'		=> 'l.log_type',
	'forum'		=> 'l.log_forum_id',
);
$available_order = array(
	'' => 'Sort_Ascending',
	'desc' => 'Sort_Descending',
);
$order_fields = array(
	'' => '',
	'desc' => ' DESC',
);
$dft_sort = 'actdays';
$dft_order = 'desc';

$actdays_list = array(0 => 'All_Logs', 1 => '1_Day', 7 => '7_Days', 14 => '2_Weeks', 30 => '1_Month', 90 => '3_Months', 180 => '6_Months', 364 =>'1_Year');

$logtypes_list = array(0 => 'All_Actions', 1 => 'Log_delete', 2 => 'Log_deletepost', 3 => 'Log_move', 4 => 'Log_lock', 5 => 'Log_unlock', 6 => 'Log_editpost', 7 =>'Log_split');

$logtypes_map = array(0 => 0, 1 => 'delete', 2 => 'deletepost', 3 => 'move', 4 => 'lock', 5 => 'unlock', 6 => 'editpost', 7 =>'split');

$parm_user_id = _read(POST_USERS_URL, TYPE_INT);
$parm_username = '';
if ( !empty($parm_user_id) )
{
	$sql = 'SELECT username
				FROM ' . USERS_TABLE . '
				WHERE user_id = ' . intval($parm_user_id);
	$result = $db->sql_query($sql, false, __LINE__, __FILE__);
	$parm_username = ($row = $db->sql_fetchrow($result)) ? $row['username'] : '';
	$db->sql_freeresult($result);
}

// get the forums list selection
$front_pic = $forums->get_front_pic();
$forums_list = array(0 => $user->lang('All_Logs'));
if ( !empty($front_pic) )
{
	foreach ( $front_pic as $cur_id => $front )
	{
		if ( $cur_id != 0 )
		{
			$option = '';
			$count_front = strlen($front);
			for ( $i = 0; $i < $count_front; $i++ )
			{
				$option .= $user->lang('tree_pic_' . $front[$i]);
			}
			if ( $cur_id > 0 )
			{
				$option .= $user->lang($forums->data[$cur_id]['forum_name']);
			}
			$forums_list[$cur_id] = $option;
		}
	}
}

$fields = array(
	'moderator' => array('type' => 'log_search_username', 'legend' => 'Search_author', 'explain' => 'Search_author_explain', 'length' => 25, 'value' => $parm_username),
	'actdays' => array('type' => 'list', 'legend' => 'More_days_old', 'options' => $actdays_list),
	'logtypes' => array('type' => 'list', 'legend' => 'Log_type', 'options' => $logtypes_list),
	POST_FORUM_URL => array('type' => 'list', 'legend' => 'Forum', 'options' => $forums_list),
	'sort' => array('type' => 'list', 'legend' => 'Sort_by', 'options' => $available_sort, 'value' => $dft_sort),
	'order' => array('type' => 'list', 'combined' => true, 'options' => $available_order, 'value' => $dft_order),
);

class log_admin extends form
{
	var $start;
	var $ppage;

	function log_admin ($requester, $parms='', &$fields)
	{
		$this->requester = $requester;
		$this->parms = empty($parms) ? array() : $parms;
		parent::form($fields);
	}

	function process()
	{
		if ( $this->init() )
		{
			$this->check();
			$this->validate();
			$this->display();
			return true;
		}
		return false;
	}

	function init()
	{
		global $db, $config, $user, $forums, $logtypes_map;
		global $sort_fields, $order_fields;
		global $dft_sort, $dbt_order;

		parent::init();
		$this->now = time();
		$this->start = _read('start', TYPE_INT);
		$this->ppage = _read('ppage', TYPE_INT, intval($config->data['logs_per_page']));
		$this->total = 0;
		$this->data = array();

		// check searches
		$moderator = preg_replace('/\*/', '%', $this->fields['moderator']->value);
		$moderator = trim(str_replace('%', '', $moderator)) == '' ? '' : $moderator;

		$actdays = $this->fields['actdays']->value;

		$logtype = $logtypes_map[$this->fields['logtypes']->value];

		$forum_id = ($this->fields[POST_FORUM_URL]->value > 0) ? $this->fields[POST_FORUM_URL]->value : 0;

		$moderator_id = _read(POST_USERS_URL, TYPE_INT);
		$moderator_ids = array();
		if ( $moderator || $moderator_id )
		{
			$sql = 'SELECT user_id
						FROM ' . USERS_TABLE . '
						WHERE ' . (empty($moderator_id) ? 'username LIKE \'' . $db->sql_escape_string($moderator) . '\'' : 'user_id = ' . intval($moderator_id));
			$result = $db->sql_query($sql, false, __LINE__, __FILE__);
			while ( $row = $db->sql_fetchrow($result) )
			{
				$moderator_ids[] = intval($row['user_id']);
			}
			$db->sql_freeresult($result);
		}

		$sql_where = array();
		if ( !empty($actdays) )
		{
			$sql_where[] = 'l.log_time > ' . ($this->now - (intval($actdays) * 86400));
		}
		if ( !empty($logtype) )
		{
			$sql_where[] = 'l.log_type = \'' . $logtype . '\'';
		}
		if ( !empty($forum_id) )
		{
			$sql_where[] = 'l.log_forum_id = ' . intval($forum_id);
		}
		if ( !empty($moderator_ids) )
		{
			$sql_where[] = 'l.log_user_id IN(' . implode(', ', $moderator_ids) . ')';
		}

		// get total of rows
		$sql = 'SELECT l.log_id
					FROM ' . LOGS_TABLE . ' l' . (empty($sql_where) ? '' : '
					WHERE ' . implode('
						AND ', $sql_where));
		$result = $db->sql_query($sql, false, __LINE__, __FILE__);
		$this->total = $db->sql_numrows($result);
		$db->sql_freeresult($result);

		// get rows
		if ( $this->total )
		{
			// get sort and order
			$sort_field = $sort_fields[ $this->fields['sort']->value ];
			$order_field = $order_fields[ $this->fields['order']->value ];

			// topics titles to get
			$post_ids = array();
			$user_ids = array();
			$req_user = $this->fields['sort']->value == 'moderator';

			$basic_fields = array(
				'l.log_id',
				'l.log_type',
				'l.log_time',
				'l.log_user_id',
				'l.log_user_ip',
				'l.log_forum_id',
				'l.log_data',
				'u.user_level',
				'u.username',
			);
			$computed_fields = array(
				'MAX(u.user_id) AS max_user_id',
				//'MAX(a.post_id) AS max_post_id',
				'COUNT(l.log_id) AS count_log_id',
			);
			if ( $req_user )
			{
				$computed_fields[] = 'MAX(u.username) AS max_username';
			}

			$sql = 'SELECT ' . implode(', ', $basic_fields) . ', ' . implode(', ', $computed_fields) . '
					FROM ' . LOGS_TABLE . ' l
					LEFT JOIN ' . USERS_TABLE . ' u
							ON u.user_id = l.log_user_id' .
					(empty($sql_where) ? '' : '
					WHERE ' . implode('
						AND ', $sql_where)) . '
					GROUP BY ' . implode(', ', $basic_fields) . '
					ORDER BY ' . $sort_field . $order_field . ', l.log_id DESC
					LIMIT ' . $this->start . ', ' . $this->ppage;

			$result = $db->sql_query($sql, false, __LINE__, __FILE__);
			while ( $row = $db->sql_fetchrow($result) )
			{

				$this->data[ intval($row['log_id']) ] = $row;
				if ( intval($row['max_user_id']) && !$req_user )
				{
					if ( isset($user_ids[ intval($row['max_user_id']) ]) )
					{
						$user_ids[ intval($row['max_user_id']) ][] = intval($row['log_id']);
					}
					else
					{
						$user_ids[ intval($row['max_user_id']) ] = array(intval($row['log_id']));
					}
				}
			}
			$db->sql_freeresult($result);

			// get usernames
			if ( !empty($user_ids) )
			{
				$sql = 'SELECT user_id, username
							FROM ' . USERS_TABLE . '
							WHERE user_id IN(' . implode(', ', array_keys($user_ids)) . ')';
				$result = $db->sql_query($sql, false, __LINE__, __FILE__);
				while ( $row = $db->sql_fetchrow($result) )
				{
					$count_attach_ids = count($user_ids[ intval($row['user_id']) ]);
					for ( $i = 0; $i < $count_attach_ids; $i++ )
					{
						$this->data[ $user_ids[ intval($row['user_id']) ][$i] ]['max_username'] = $row['username'];
					}
				}
				$db->sql_freeresult($result);
			}
			unset($user_ids);
		}

		return true;
	}

	function check()
	{
		global $config, $user;
		global $error, $error_msg;

		if ( _button('submit_form') )
		{
			parent::check();
		}
		if ( $error )
		{
			message_return($error_msg, 'Click_return_logs', $config->url($this->requester, $this->parms, true));
		}
	}

	function validate()
	{
		global $db, $config, $user;

		$return_msg = '';
		if ( _button('delete_details') )
		{
			// get vars
			$log_ids = get_var('log_ids', array(0));
			$log_ids = empty($log_ids) ? array() : array_flip($log_ids);
			$delete_box = get_var('delete_box', array(0));
			$delete_box = empty($delete_box) ? array() : array_flip($delete_box);

			$deleted_ids = array();
			foreach ( $this->data as $log_id => $data )
			{
				if ( isset($log_ids[$log_id]) )
				{
					$idx = $log_ids[$log_id];
					if ( _button('delete_details') )
					{
						if ( isset($delete_box[$log_id]) )
						{
							$deleted_ids[] = $log_id;
						}
					}
				}
			}

			if ( $count_deleted_ids = count($deleted_ids) )
			{

				// delete logs
				$sql = 'DELETE FROM ' . LOGS_TABLE . '
							WHERE log_id IN(' . implode(', ', $deleted_ids) . ')';
				$db->sql_query($sql, false, __LINE__, __FILE__);

				// prepare return
				$return_msg = 'Logs_deleted';
			}
			unset($deleted_ids);

			// return message
			if ( !empty($return_msg) )
			{
				message_return($return_msg, 'Click_return_logs', $config->url($this->requester, $this->get_link_parms(), true));
			}
		}
	}

	function get_link_parms()
	{
		global $dft_sort, $dft_order;

		$parms = $this->parms;
		if ( $this->fields['sort']->value != $dft_sort )
		{
			$parms['sort'] = $this->fields['sort']->value;
		}
		if ( $this->fields['order']->value != $dft_order )
		{
			$parms['order'] = $this->fields['order']->value;
		}
		if ( trim($this->fields['moderator']->value) != '' )
		{
			$parms['moderator'] = rawurlencode($this->fields['moderator']->value);
		}
		if ( intval($this->fields['actdays']->value) )
		{
			$parms['actdays'] = intval($this->fields['actdays']->value);
		}
		if ( intval($this->fields['logtypes']->value) )
		{
			$parms['logtypes'] = intval($this->fields['logtypes']->value);
		}
		if ( intval($this->fields[POST_FORUM_URL]->value) )
		{
			$parms[POST_FORUM_URL] = intval($this->fields[POST_FORUM_URL]->value);
		}
		return $parms;
	}

	function display()
	{
		global $db, $template, $user, $config, $forums;
		global $sort_fields, $order_fields;
		global $dft_sort, $dbt_order;

		// display search form
		foreach ( $this->fields as $field_name => $field )
		{
			$this->fields[$field_name]->display();
		}
		display_buttons($this->buttons);
		$template->assign_vars(array('SEARCH_FORM' => $template->include_file('form_fields.tpl', array('field'))));

		// display details
		if ( !empty($this->data) )
		{
			$color = false;
			$i = 0;
			foreach ( $this->data as $log_id => $row )
			{
				$i++;
				$color = !$color;
				$row_data = unserialize($row['log_data']);
				$log_data = array();
				switch ($row['log_type'])
				{
					case 'move':
						$log_data['U_VIEWFORUM_NEW'] = $config->url('index', array(POST_FORUM_URL => $row_data['new_forum']), true);
						$log_data['FORUM_NAME_NEW'] = $user->lang($forums->data[$row_data['new_forum']]['forum_name']);
						break;
					case 'editpost':
						$log_data['U_POST'] = $config->url('viewtopic', array(POST_POST_URL => $row_data['post_id']), true, $row_data['post_id']);
					case 'deletepost':
						$log_data['U_TOPIC'] = $config->url('viewtopic', array(POST_TOPIC_URL => $row_data['topic_id']), true);
						$log_data['TOPIC_TITLE'] = $row_data['topic_title'];
						break;
					case 'split':
						$log_data['U_VIEWFORUM_NEW'] = $config->url('index', array(POST_FORUM_URL => $row_data['new_forum_id']), true);
						$log_data['FORUM_NAME_NEW'] = $user->lang($forums->data[$row_data['new_forum_id']]['forum_name']);
						$log_data['U_TOPIC_OLD'] = $config->url('viewtopic', array(POST_TOPIC_URL => $row_data['old_topic_id']), true);
						$log_data['TOPIC_TITLE_OLD'] = $row_data['old_topic_title'];
						$log_data['U_TOPIC_NEW'] = $config->url('viewtopic', array(POST_TOPIC_URL => $row_data['new_topic_id']), true);
						$log_data['TOPIC_TITLE_NEW'] = $row_data['new_topic_title'];
						break;
				}

				$template->assign_block_vars('row', $log_data + array(
					'ROW_NUMBER' => $i,
					'LOG_ID' => $log_id,
					'DATE' => $user->date($row['log_time']),
					'U_USERNAME' => ($row['username']) ? $config->url('usercp', array(POST_USERS_URL => intval($row['max_user_id'])), true) : '',
					'USERNAME' => $row['username'],
					'USER_IP' => empty($row['log_user_ip']) ? '' : decode_ip($row['log_user_ip']),
					'U_USER_IP' => $config->data['log_user_ip_action_url'] . decode_ip($row['log_user_ip']),
					'U_VIEWFORUM' => $config->url('index', array(POST_FORUM_URL => $row['log_forum_id']), true),
					'FORUM_NAME' => $forums->data[$row['log_forum_id']]['forum_name'],
				));
				$template->set_switch('row.light', $color);
				$template->set_switch('row.' . $row['log_type'], true);
				$template->set_switch('row.user_link', intval($row['max_user_id']));
				switch ($row['log_type'])
				{
					case 'lock':
					case 'move':
					case 'unlock':
					case 'delete':
						foreach ( $row_data['topics'] as $topic_id => $topic )
						{
							$template->assign_block_vars('row.'.$row['log_type'].'.topic', array(
								'U_TOPIC' => $config->url('viewtopic', array(POST_TOPIC_URL => $topic_id), true),
								'TOPIC_TITLE' => $topic,
							));
						}
						break;
					case 'split':
						foreach ( $row_data['posts'] as $post_id )
						{
							$template->assign_block_vars('row.'.$row['log_type'].'.post', array(
								'U_POST' => $config->url('viewtopic', array(POST_POST_URL => $post_id), true),
								'POST_ID' => $post_id,
							));
						}
						break;
				}
			}
		}

		// display header
		$template->assign_vars(array(
			'L_VIEW_POST' => $user->lang('View_post'),
			'L_VIEWFORUM' => $user->lang('View_forum'),
			'L_IP_ADDRESS' => $user->lang('IP_Address'),
			'L_DATE' => $user->lang('Date'),
			'L_FORUM' => $user->lang('Forum'),
			'L_MOVED_TO' => $user->lang('Moved_to'),
			'L_TOPICS_MOVE' => $user->lang('Topics_moved'),
			'L_TOPICS_LOCK' => $user->lang('Topics_locked'),
			'L_TOPICS_UNLOCK' => $user->lang('Topics_unlocked'),
			'L_TOPICS_DELETE' => $user->lang('Topics_deleted'),
			'L_TOPICS_SPLIT' => $user->lang('Topics_split'),
			'L_POST_EDIT' => $user->lang('Post_edited'),
			'L_POST_DELETE' => $user->lang('Post_deleted'),
			'L_POST_SPLIT' => $user->lang('Post_split'),
			'L_IN' => $user->lang('In'),
			'L_USERNAME' => $user->lang('Username'),
			'L_DETAILS' => $user->lang('Log_Details'),
			'L_NO_MATCHES' => $user->lang('No_logs_match'),
			'L_POSTS_FROM' => $user->lang('Posts_from'),
		));
		$template->set_switch('details');
		$details_buttons = array(
			'delete_details' => array('txt' => 'Delete_marked', 'img' => 'cmd_delete', 'key' => 'cmd_delete'),
		);
		display_buttons($details_buttons, 'details');

		$parms = $this->get_link_parms();
		$pagination = new pagination($this->requester, $parms);
		$pagination->display('pagination', $this->total, $this->ppage, $this->start, true, 'Logs_count');
		unset($pagination);

		// send all to template
		$template->assign_block_vars('cp_content', array('BOX' => $template->include_file('acp/acp_advlog_box.tpl')));

	}
}

// instantiate the display
$parms = array(
	'mode' => $menu_id,
	'sub' => $subm_id == $menu_id ? '' : $subm_id,
	'ctx' => $ctx_id == $subm_id ? '' : $ctx_id,
);
$form = new log_admin($cp_requester, $cp_parms + $parms, $fields);
$form->process();
$template->set_filenames(array('body' => 'cp_generic.tpl'));

?>